#include "macaction.h"
#include "vtable.h"
#include "DbConnection.h"
#include "treedoc.h"
#include "disparition.h"
#include "dateedit.h"
#include <QDebug>
#include <QVBoxLayout>

MacAction::MacAction(const bool &Inner, QTreeWidget *parent) :
    DocEntity(parent), m_inner(Inner)
{
    DbConnection::QueryResult res = dynamic_cast<TreeDoc*>(treeWidget())
                                    ->execute("select * from =schema=.ex_operations where element_type=1");
    if(res.success())
    {
        for(int i=0;i<res.rows();i++)
        {
            QAction* action =new QAction(res.at(i,2).toString(),this);
            if(res.at(i,1).toInt()==2)
            {
                connect(action,SIGNAL(triggered()),this,SLOT(appendDisparition()));
                action->setIcon(QIcon(":/add_entity"));
            }
            if(res.at(i,1).toInt()==5)
            {
                connect(action,SIGNAL(triggered()),this,SLOT(save()));
                action->setIcon(QIcon(":/save_entity"));
            }
            if(res.at(i,1).toInt()==9)
            {
                connect(action,SIGNAL(triggered()),this,SLOT(remove()));
                action->setIcon(QIcon(":/delete_entity"));
            }
            if(action!=0) operations()->addOperation(res.at(i,1).toInt(),action);
        }
        QAction* action = new QAction(QIcon(":/refresh"),tr("Обновить"),this);
        connect(action,SIGNAL(triggered()),this,SLOT(refresh()));
        operations()->addOperation(50,action);
        operations()->setEnabled(50,true);
    }
}
bool MacAction::removeFromDB()
{
    return dynamic_cast<TreeDoc*>(treeWidget())
                                    ->execute(tr("select =schema=.ex_delete_macAction(%1)").arg(id())).success();
}
void MacAction::setAuthor(User *user)
{
    m_author=user;
    emit changed();
}

void MacAction::setExpiry(const QDate &Expiry)
{
    m_expiry=Expiry;
    emit changed();
}

User* MacAction::author()
{
    return m_author;
}

QDate MacAction::expiry() const
{
    return m_expiry;
}

void MacAction::giveBithTo()
{
    DbConnection::QueryResult res=dynamic_cast<TreeDoc*>(treeWidget())->
                              execute(tr("select * from =schema=.ex_disparitions where mac_action=%1").arg(id()));
    for(int i=0;i<res.rows();i++)
    {
        Disparition* item=new Disparition(this);
        item->blockSignals(true);
        item->setID(res.at(i,0).toInt());
        item->setNum(res.at(i,2).toInt());
        item->setContent(res.at(i,3).toString());
        item->setState(res.at(i,4).toInt());
        item->blockSignals(false);
        if(dynamic_cast<TreeDoc*>(treeWidget())->highlight()) emit newItem(item);
        QStringList ops = res.at(i,5).toString().replace(QRegExp("[{}]"),"").split(",",QString::SkipEmptyParts);
        if(ops.count()==0) continue;
        foreach(QString id,ops) item->operations()->setEnabled(id.toInt(),true);
    }
}
void MacAction::refresh(const RefreshType &refreshType)
{

        DbConnection::QueryResult res=dynamic_cast<TreeDoc*>(treeWidget())->
                                  execute(tr("select * from =schema=.ex_mac_actions where eid=%1").arg(id()));

        if(res.success())
        {
            blockSignals(true);
            setID(res.at(0,0).toInt());
            setNum(res.at(0,1).toInt());
            UserList* list = dynamic_cast<TreeDoc*>(treeWidget())->users();
            setAuthor(list->user(res.at(0,2).toInt()));
            setExpiry(res.at(0,3).toDate());
            setState(res.at(0,5).toInt());
            blockSignals(false);
            operations()->turnOff();
            operations()->setEnabled(50,true);
            QStringList ops = res.at(0,6).toString().replace(QRegExp("[{}]"),"").split(",",QString::SkipEmptyParts);
            if(ops.count()>0)
                foreach(QString id,ops) operations()->setEnabled(id.toInt(),true);
        }
    if(refreshType==Himself)
    {
        emit wasRefresh();
        emit childWakedUp(this);
    }
    if(refreshType==Children)
    {
        for(int i=0;i<childCount();i++)
            dynamic_cast <Disparition*>(child(i))->refresh(Children);
    }
}
QWidget* MacAction::view(DocEntity::ViewTypes viewType)
{
    QWidget* widget = new QWidget(treeWidget());
    QVBoxLayout* main = new QVBoxLayout;
    main->setContentsMargins(0,0,0,0);
    QHBoxLayout* hlay = new QHBoxLayout;
    QVBoxLayout* l_vlay = new QVBoxLayout;
    l_vlay->addWidget(new QLabel(tr("Дата совещания"),widget));
    l_vlay->addWidget(new QLabel(tr("Инициатор"),widget));
    l_vlay->addWidget(new QLabel(tr("Тип"),widget));
    hlay->addLayout(l_vlay);
    QVBoxLayout* r_vlay = new QVBoxLayout;
    DateEdit* w_expiry = new DateEdit(widget);
    w_expiry->blockSignals(true);
    connect(w_expiry,SIGNAL(dateChanged(QDate)),this,SLOT(setExpiry(QDate)));
    r_vlay->addWidget(w_expiry);
    w_expiry->setDate(expiry());
    w_expiry->blockSignals(false);
    w_expiry->setEnabled(operations()->isEnabled(5));
    QLineEdit* w_author = new QLineEdit(widget);
    w_author->setReadOnly(true);
    w_author->setEnabled(false);
    w_author->setText(author()->name());
    r_vlay->addWidget(w_author);
    QLineEdit* w_type = new QLineEdit(widget);
    w_type->setReadOnly(true);
    w_type->setEnabled(false);
    w_type->setText(inner()?tr("Внутрецеховые"):tr("Общезаводские"));
    r_vlay->addWidget(w_type);
    hlay->addStretch();
    hlay->addLayout(r_vlay);
    QGroupBox* gbox = new QGroupBox(text(0),widget);
    gbox->setLayout(hlay);

    main->addWidget(gbox);
    if(viewType==Normal)
    {
        QLineEdit* line = new QLineEdit(widget);
        line->setReadOnly(true);
        line->setEnabled(false);
        line->setText(status());
        l_vlay->addWidget(new QLabel(tr("Статус"),widget));
        r_vlay->addWidget(line);

        vTable* table = new vTable;
        int n=0;
        for(int i=0;i<childCount();i++)
            if(!child(i)->isHidden()) n++;
        table->setSize(n,3);
        table->setColSettings("5%;75%;15%");
        table->setHorizontalHeaderLabels(QStringList()<<tr("№")<<tr("Несоответствие")<<tr("Статус"));
        int k=0;
        for(int i=0;i<childCount();i++)
        {
            Disparition* item = dynamic_cast<Disparition*>(child(i));
            if(item->isHidden()) continue;
            table->setCell(k,0,item->num());
            table->setCell(k,1,item->content());
            table->setCell(k,2,item->status());
            k++;
        }
        connect(table,SIGNAL(cellActivated(int,int)),this,SLOT(onTableItemClick(int,int)));
        gbox = new QGroupBox(tr("Несоответствия"),widget);
        hlay=new QHBoxLayout;
        hlay->addWidget(table);
        gbox->setLayout(hlay);
        main->addWidget(gbox);
    }
    widget->setLayout(main);
    return widget;
}

void MacAction::onTableItemClick(int row, int column)
{
    emit childWakedUp(dynamic_cast<DocEntity*>(child(row)));
}

QString MacAction::capTemplate()
{
    return tr("КД/ПД");
}

void MacAction::appendDisparition()
{
    Disparition* item = new Disparition(this);
    item->setID(0);
    item->setNum(childCount());
    item->setContent("");
    item->setState(200);
    treeWidget()->setCurrentItem(item);
    item->operations()->setEnabled(3,true);
    item->operations()->setEnabled(6,true);
    item->operations()->setEnabled(10,true);
    emit newItem(item);
    emit childWakedUp(item);
}

bool MacAction::saveToDB()
{
    bool ok=isCorrect(), stop=false;

    if(id()==0)
    {
        QString sql="select =schema=.ex_append_macaction(%1,'%2'::timestamp,%3)";
        sql=sql.arg(num()).arg(expiry().toString("yyyy-MM-dd")).arg((inner()?"true":"false"));
        DbConnection::QueryResult res = dynamic_cast<TreeDoc*>(treeWidget())->execute(sql);
        if(res.success())
            setID(res.at(0,0).toInt());
        else
            ok=false;
    }
    else
    {
        QString sql="select =schema=.ex_change_macaction(%1,'%2'::timestamp,%3)";
        sql=sql.arg(id()).arg(expiry().toString("yyyy-MM-dd")).arg(num());
        DbConnection::QueryResult res = dynamic_cast<TreeDoc*>(treeWidget())->execute(sql);
        ok=res.success();
    }
    if(ok)setChanged(false);
    if(!ok) return false;
    int i=0;
    while(ok&&!stop)
    {
        stop=(i>=childCount());
        if(!stop) ok=dynamic_cast<DocEntity*>(child(i))->saveToDB();
        i++;
    }
    if(!ok) return false;
    return ok;
}
bool MacAction::isCorrect()
{
    return true;
}
bool MacAction::inner() const
{
    return m_inner;
}

